﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MISAPP.Classify.DataAccess;
using MISAPP.MISInterface;

namespace MISAPP.Classify.Service
{
    public class Service_ARTM95_ABCDE : MISAPP.MISInterface.iAutoComplete
    {
        public enum AccNoOption
        {
            Accno123 = 1, Accno45, AccWMG, AccnoDefault
        }

        DA_ARTM95_ABCDE artm95 = null;
        DA_ARTM95_ABCDE DA
        {
            get
            {
                if (artm95 == null)
                {
                    artm95 = new DA_ARTM95_ABCDE();
                }
                return artm95;
            }
        }

        #region iAutoComplete Members

        public DataTable GetAutoCompleteTable(string p_qry)
        {
            if (string.Empty.Equals(p_qry))
            {
                return null;
            }
            DA.ResetCriteria();
            return DA.GetAC001Info(p_qry);
        }

        #endregion

        public DataSet GetCriteriaData()
        {
            return DA.GetCriteria();
        }

        public string[] GetCriteriaArray()
        {
            return DA.GetDistinctField();
        }

        public DataTable GetSummaryData(System.Collections.ArrayList p_criteria)
        {
            StringBuilder sb = new StringBuilder();
            DataTable dt = null;
            string accno1, accno2, year;
            try
            {
                DA.ResetCriteria();
                List<iSelectList> criteriaList = p_criteria[0] as List<iSelectList>;
                foreach (SelectList SL in criteriaList)
                {
                    if (SL.IsGroupBy() & (SL.GetListCount() > 0))
                    {
                        sb.AppendFormat(",{0}", SL.GetField());
                    }
                    DA.AddCriteria(SL.GetField(), DA.GetInString(SL.GetReverse()), SL.GetListArray());
                }
                List<string> accBetween = p_criteria[1] as List<string>;
                year = p_criteria[2].ToString();
                string opt = Convert.ToInt16(p_criteria[3].ToString()).ToString();
                bool showTotal = Convert.ToBoolean(p_criteria[4]);
                accno1 = accBetween[0];
                accno2 = accBetween[1];
                DA.SetGroupByString(sb.ToString());
                dt = DA.GetSummaryData(accno1, accno2, opt, year, showTotal);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dt;
        }

        public DataTable GetSummaryData2(System.Collections.ArrayList p_criteria)
        {
            string yr = p_criteria[0].ToString();
            string[] flds = { "big", "small", "branch" };
            string[] accs = p_criteria[1].ToString().Split(
                    new char[] { '_' });
            DA.ResetCriteria();
            for (int i = 2; i <= p_criteria.Count; i++)
            {
                string[] tmp = p_criteria[i].ToString().Split(
                    new char[] { '_' });
                if (tmp.Count() > 0)
                {
                    DA.AddCriteria(flds[i], " IN ", tmp);
                }
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="p_ym">YYYYYMM</param>
        /// <returns></returns>
        public DataTable GetDebtSummaryData(System.Collections.ArrayList p_criteria)
        {
            string ym = p_criteria[0] as string;
            DataTable dt = null;
            DateTime d1 = Utility.GetLastDate(ym);
            dt = DA.GetDebtSummaryData(d1);
            return dt;
        }

        /// <summary>
        /// 未來所有從Excel取得會計資料的部份都由這個Method 當成入口
        /// </summary>
        /// <param name="p_criteria"></param>
        /// <returns></returns>
        public DataTable GetDataFromWeb(System.Collections.ArrayList p_criteria)
        {
            /*
            * para = YYYYMM
            * bg = 大版塊
            * sm = 小版塊
            * br = 分行
            * cr = 幣別
            * mthd = Data Object 這一個Method
             */
            System.Collections.ArrayList al1 = p_criteria[0] as
                System.Collections.ArrayList;
            string ym, mthd;
            string[] fields = DA.GetFeildForExcle();
            ym = al1[0] as string;
            mthd = al1[5] as string;
            System.Collections.ArrayList al =
                new System.Collections.ArrayList();
            DA.ResetCriteria();
            DateTime d1 = DateTime.MinValue;
            DateTime d2 = DateTime.MinValue;

            Dictionary<string, string> paraDict = new Dictionary<string, string>();

            for (int i = 1; i < al1.Count - 1; i++)
            {
                string[] tmp = al1[i].ToString().Split(
                    new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                if (tmp.Count() > 0)
                {
                    //DA.AddCriteria(fields[i], "IN", tmp);
                    paraDict.Add(fields[i], al1[i].ToString());
                }
            }

            List<object> paraObjList = new List<object>();


            //日期區間YYYYMM_YYYYMM
            if (ym.IndexOf('_') < 1)
            {
                if (mthd.Equals("GetTMUData"))
                {
                    paraObjList.Add(getTMU4Date(ym));
                }
                else
                {
                    d1 = Utility.GetLastDate(ym);
                    paraObjList.Add(d1);
                }
            }
            else
            {
                string[] yms = ym.Split('_');
                paraObjList.Add(new object[] {
                    Utility.GetLastDate(yms[0])
                    , Utility.GetLastDate(yms[1])
                    ,paraDict
                });
            }
            System.Reflection.MethodInfo mi = DA.GetType().GetMethod(mthd);
            DataTable dt = null;
            try
            {
                 dt = mi.Invoke(DA, paraObjList.ToArray()) as DataTable;
            }
            catch (Exception ex)
            { 
            
            }
            return dt;
        }

        public DataTable Trans2XLS(System.Collections.ArrayList p_criteria)
        {
            DataTable dt = this.GetSummaryData(p_criteria);
            dt.Columns[0].MaxLength = 13; //修改長度，讓下面可以把值順利加入
            dt.Columns[4].MaxLength = 6;

            //這是為了讓資料轉到excel 時可以被篩選，還有讓如果開頭是0的
            //不會消失
            IEnumerable<DataRow> results = from myRow in dt.AsEnumerable()
                                           select myRow;
            results.ToList().ForEach(r =>
            {
                r[0] = "=\"" + r[0].ToString() + "\"";
                r[4] = "=\"" + r[4].ToString() + "\"";
            });

            System.Data.DataTable dtZZZ = results.CopyToDataTable<DataRow>();
            return dtZZZ;
        }

        /*
        public DataTable GetSummaryData_BAK(System.Collections.ArrayList p_criteria)
        {
            string accno1, accno2,date1,date2;

            DataTable dt = null;
            try
            {
                DA.ResetCriteria();
                List<iSelectList> criteriaList = p_criteria[0] as List<iSelectList>;
                foreach (SelectList SL in criteriaList)
                {
                    DA.AddCriteria(SL.GetField(), DA.GetInString(SL.GetReverse()), SL.GetListArray());
                }

                List<string> dateBetween = p_criteria[1] as List<string>;
                List<string> accBetween = p_criteria[2] as List<string>;
                accno1 = accBetween[0];
                accno2 = accBetween[1];
                date1 = dateBetween[0];
                date2 = dateBetween[1];
                dt = DA.GetSummaryData_BAK(accno1,accno2,date1,date2);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dt;
        }
        */

        /// <summary>
        /// 用來檢查會計科目開頭是否為1、2、3
        /// </summary>
        /// <param name="p_accno"></param>
        /// <returns></returns>
        public bool AccountNoIs123(string p_accno)
        {
            bool result = true;
            string subAccno = p_accno.Substring(0, 1);
            switch (subAccno)
            {
                case "1":
                    break;
                case "2":
                    break;
                case "3":
                    break;
                default:
                    result = false;
                    break;
            }
            return result;
        }

        public bool AccountNoIs45(string p_accno)
        {
            bool result = true;
            string subAccno = p_accno.Substring(0, 1);
            switch (subAccno)
            {
                case "4":
                    break;
                case "5":
                    break;
                default:
                    result = false;
                    break;
            }
            return result;
        }

        public DataTable GetAccInfo2(string p_accNo, string p_accName)
        {
            DataTable dt = DA.GetAC001Info2(p_accNo, p_accName);
            return dt;
        }

        /// <summary>
        /// 取回四個日期
        /// </summary>
        /// <returns></returns>
        protected object[] getTMU4Date(string p_ym)
        {
            //給TMU 來使用
            /*12月的處理？？
             * {0} 本期
             * {1} 前期
             * {2} 前一年的本期
             * {3} 本期的第一個月
             * {4} 前一年的本期的第一個月
             */
            string d3Str,d2Str;
            d3Str = "{0}-1-31" ;
            d2Str = "{0}-{1}-1";
            DateTime d0,d1,d2,d3,d4;
            d0 = Utility.GetLastDate(p_ym);
            d1 = d0.AddDays(1).AddMonths(-1).AddDays(-1);
            d2 = Convert.ToDateTime(string.Format(d2Str, d0.Year.ToString()
                , d0.Month.ToString()));
            d2 = d2.AddYears(-1).AddMonths(1).AddDays(-1);
            //d2 = d0.AddYears(-1);
            d3 = Convert.ToDateTime(string.Format(d3Str, d0.Year.ToString())) ;
            d4 = Convert.ToDateTime(string.Format(d3Str, d2.Year.ToString()));
            return new object[]{d0.ToShortDateString()
                ,d1.ToShortDateString(),d2.ToShortDateString()
                ,d3.ToShortDateString(),d4.ToShortDateString()};
        }

    }
}
